//
//  LiveViewControllerViewController.swift
//  LearnDemo
//
//  Created by 振轩 on 2018/4/3.
//  Copyright © 2018年 振轩. All rights reserved.
//


let urlheader = "http://192.168.1.97:8080/"
import UIKit
let VideoCell = "VideoCell"
let titleCell = "titleCell "
class LiveViewControllerViewController: UIViewController {
    var ReqM:ReqMode?
    
    var timer =  DispatchSource.makeTimerSource(flags: [], queue:DispatchQueue.main)
    var currentPlayTime:NSInteger = 0
    var configration = SelPlayerConfiguration()
    var data:ArticleDetail?
    var player:SelVideoPlayer?
    var titleView:VideoTitleView?
    lazy  var tableView:UITableView = {
     let tableview = UITableView.init(frame: CGRect(x: 0, y: videoHeight+5, width: kScreenW, height: kScreenH-videoHeight-10+5))
        tableview.delegate = self as? UITableViewDelegate
         tableview.dataSource = self
         tableview.register(UINib.init(nibName: "VideoTableViewCell", bundle: nil), forCellReuseIdentifier: VideoCell)
        tableview.register(UINib.init(nibName: "VideoTitleCell", bundle: nil), forCellReuseIdentifier: titleCell)
        
        //view.addSubview(tableview)
        tableview.rowHeight = 102
        return tableview
        
    }()
    override func viewDidLoad() {
        
        
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(stop), name: NSNotification.Name(rawValue: "stop"), object: nil)
        
        setUpTitleView()
        setUpUI()
        loadData()
        setUpTimer()

        // Do any additional setup after loading the view.
    }
    func setUpTimer(){
        
        timer.scheduleRepeating(deadline: .now(), interval: .seconds(20) ,leeway:.milliseconds(40))
        
        timer.setEventHandler {
            
            self.upLoad()
            
        }
        
    }
    
//    #pragma mark    禁止横屏
//    - (UIInterfaceOrientationMask )application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
//    {
//    if (self.allowRotation) {
//    return UIInterfaceOrientationMaskAll;
//    }
//    return UIInterfaceOrientationMaskPortrait;
//    }
    
    
    
    override func viewDidAppear(_ animated: Bool) {
        
    }
    
    
    @objc func stop(){
         NotificationCenter.default.post(name: NSNotification.Name.init("cancelFull"), object: nil)
         upLoad()
        self.dismiss(animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        
        
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        player?._deallocPlayer()
    }
    deinit {
       // NotificationCenter.default.removeObserver(self)
        
       // player = nil
    }
    
 
    
}
extension LiveViewControllerViewController{
    
    func startLive(){
        view.backgroundColor = UIColor.white
        if UIDevice.current.systemVersion > "7.0" {
            edgesForExtendedLayout = UIRectEdge()
        }
        configration.shouldAutoPlay = true;
        configration.supportedDoubleTap = true;
        configration.shouldAutorotate = false;
        configration.repeatPlay = true;
        configration.statusBarHideState = SelStatusBarHideState.followControls;
        configration.sourceUrl = URL.init(string:(ReqUrl+(self.data?.videoUrl)!))
        
        
        configration.videoGravity = SelVideoGravity.resizeAspect
        player = SelVideoPlayer(frame: CGRect(x: 0, y: 0, width: kScreenW, height: videoHeight), configuration: configration)
        if #available(iOS 10.0, *) {
            timer.activate()
        } else {
            
                  
        }
        view.addSubview(player!)
        if self.currentPlayTime != nil {
            player?.palay(with: currentPlayTime)
        }
    }
    
    //设置tileView.
    func setUpTitleView(){
        
        titleView = VideoTitleView.loadTitleView()
        
        titleView?.frame = CGRect(x: 0, y: 202, width: kScreenW, height:172)
       // view.addSubview(titleView!)
       // print(titleView?.frame ?? "0")
        
    }
    func setUpUI(){
        
        view.addSubview(tableView)
    }
    
}


///tableviewDelegate.

extension LiveViewControllerViewController:UITableViewDataSource,UITabBarDelegate,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        
        if section == 0 {
            return 1
        }else{
            
            return data?.relatedList?.count ?? 0
        }
        
        
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: titleCell, for: indexPath) as! VideoTitleCell
            cell.mode = data
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCell, for: indexPath) as! VideoTableViewCell
            cell.mode = data?.relatedList![indexPath.row] as? videoSub
            return cell
        }
        
    }
    
    
    func loadData(){
        
        var params = [String:AnyObject]()
        params["courseId"] = ReqM?.courseId as AnyObject
        params["staffId"] = ReqM?.staffId as AnyObject
        params["staffType"] = ReqM?.staffType as AnyObject
        let API:BaseReqApi = BaseReqApi.init(requestUrl: "/index.php/FoodCheckApi/courseDetail.json", andrequestTime: 5, andParams: params as! [AnyHashable : Any], andRequestMethod: YTKRequestMethod.POST, andCache: false, andCacheTime: 0, andPostToken: true)
        
        API.starRequest { (status, mess, response) in
            
            guard let dic:Dictionary = response as? [String : AnyObject] else{
                
                return
            }
            print("_______***______")
            print(dic)
            
             print("_______***______")
            let mode1  = CourseDetail.init(DIC: dic)
            
           if status.rawValue == 1  {
                
                self.data = mode1.data as! ArticleDetail
                if self.player != nil{
                    
                    
                    self.player?._deallocPlayer()
                    self.player = nil
                    
                }
                self.startLive()
                
                self.tableView.reloadData()
            
                self.titleView?.mode = self.data
            
             }else if (status.rawValue == 404){
            
            UIAlertView.bk_show(withTitle: mess, message: "", cancelButtonTitle: "登陆", otherButtonTitles: ["取消"], handler: { (alertView, buttonIndex) in
                if(buttonIndex == 0){
                    self.gotoLogin()
                }
            })
            
            }else{
            print(status)
            print(mess)
            
            }
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        
        let mode = self.data?.relatedList![indexPath.row] as! videoSub
        
        self.ReqM?.courseId = mode.id
        
        loadData()
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 171
        }else{
            return 102
            
        }
    }
//
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        return titleViewH
//    }
    
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
//
//        if section == 0 {
//            return self.titleView
//        }else{
//
//            return nil
//        }
//    }
    
    
    
    //上传进度。
    func upLoad(){
        if self.player?.playerState == SelVideoPlayerState.playing   {
            var params = [String:AnyObject]()
            params["courseId"] = ReqM?.courseId as AnyObject
            params["staffId"] = ReqM?.staffId as AnyObject
            params["staffType"] = ReqM?.staffType as AnyObject
            params["totalPlayTime"] = self.player?.totalTime as AnyObject
            params["currentPlayTime"] = self.player?.currentTime as AnyObject
            var progress:Int = 0
            if (self.player?.currentTime)!>1{
                progress = ((self.player?.currentTime)!*100)/(self.player?.totalTime)!
            
            }else{
                
                progress = 1
            }
            params["progress"] = progress as AnyObject
            //params["progress"] = 60 as AnyObject
            print(params)
            let API:BaseReqApi = BaseReqApi.init(requestUrl: "/index.php/FoodCheckApi/courseRecord.json", andrequestTime: 5, andParams: params as! [AnyHashable : Any], andRequestMethod: YTKRequestMethod.POST, andCache: false, andCacheTime: 0, andPostToken: true)
            
            API.starRequest { (status, mess, response) in
                
                guard let dic:Dictionary = response as? [String : AnyObject] else{
                    
                    return
                }
                print("_______***______")
                print(dic)
                print("_______***______")
                
            }
            }
            
        }
}
